﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Web;

/// <summary>
/// Expand 的摘要说明
/// </summary>
public static class Expand
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="conn"></param>
    /// <param name="Timeout">设置超时的时间，单位为（秒），默认3秒，支持小数位的毫秒。</param>
    public static void Open(this SqlConnection conn, double Timeout = 3.0)
    {
        conn.OpenDb(Timeout);
    }
    /// <summary>
    /// 用线程的方式执行SqlConnection.Open()
    /// </summary>
    /// <param name="conn"></param>
    /// <param name="Timeout">设置超时的时间，单位为（秒），默认3秒，支持小数位的毫秒。</param>
    public static void OpenDb(this SqlConnection conn, double Timeout = 3.0)
    {
        bool successed = false;
        var thread = new Thread(() =>
        {
            try
            {
                if (ConnectionState.Open == conn.State)
                {
                    successed = true;
                }
                else
                {
                    conn.Open();
                    successed = true;
                }
            }
            catch (SqlException ex)
            {
                //throw ex;
            }
            catch (ThreadAbortException)
            {
            }
            catch (InvalidOperationException)
            {
            }
            catch (Exception)
            {
            }
        });
        thread.IsBackground = true;
        Stopwatch sw = Stopwatch.StartNew();
        thread.Start();
        TimeSpan timeout = TimeSpan.FromSeconds(Timeout);
        while (sw.Elapsed < timeout)
        {
            thread.Join(TimeSpan.FromMilliseconds(200));
        }
        sw.Stop();
        if (!successed)
        {
            throw new Exception("超时无法连接.");
        }
    }
    public static void CloseDb(this SqlConnection conn)
    {
        if (ConnectionState.Open == conn.State) conn.Close();
    }
}